package com.it.tydic.estate.module.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.util.InstaIdGenerator;
import com.it.tydic.estate.common.util.StringUtils;
import com.it.tydic.estate.common.util.TimeUtil;
import com.it.tydic.estate.module.mapper.inner.TbCkglRkckdmxMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglRkckglMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWpdaMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWpkcMapper;
import com.it.tydic.estate.module.model.inner.*;
import com.it.tydic.estate.module.service.RkglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.*;

@Transactional
@Service
public class RkglServiceImpl implements RkglService {

    @Autowired
    private TbCkglRkckglMapper rkglMapper;

    @Autowired
    private TbCkglRkckdmxMapper rkdmxMapper;

    @Autowired
    private TbCkglWpkcMapper wpkcMapper;

    @Autowired
    private TbCkglWpdaMapper wpdaMapper;

    /**
     * 物品档案新增修改
     * @param rkgl
     * @return
     */
    @Override
    public Result insertOrUpdate(TbCkglRkckgl rkgl) {
        //必传项参数校验
        if(StringUtil.isEmpty(rkgl.getDjbh()) || rkgl.getFsrq()==null || StringUtil.isEmpty(rkgl.getUserId())
                || StringUtil.isEmpty(rkgl.getJsr()) || StringUtil.isEmpty(rkgl.getSzck())){
            return  Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        if(StringUtil.isEmpty(rkgl.getId())){//判断如果为空新增
            //首先新增入库单信息
            rkgl.setId(String.valueOf(new InstaIdGenerator().nextId(TimeUtil.timeGen())));
            rkgl.setZfbj("0");
            rkgl.setCreateTime(new Date());
            rkgl.setUpdateTime(new Date());
            rkgl.setShzt(0);//设置默认审核单据为未审核 0
            rkgl.setDjlb("0");//设置单据类别为 入库
            int index = rkglMapper.insert(rkgl);
            if(index==1){
                //保存入库单详情信息
                addRkdxq(rkgl);
                return Result.success(rkgl.getId());
            }else {
                return  Result.error(CodeMsg.INSERT_ERROR);
            }
        }else {
            //首先修改入库管理
            rkgl.setUpdateTime(new Date());
            int index = rkglMapper.updateByPrimaryKeySelective(rkgl);
            if(index==1){
                //修改入库单明细表
                //uodateRkdxq(rkgl);
                return Result.success();
            }else {
                return  Result.error(CodeMsg.UPDATE_ERROR);
            }
        }
    }

    /**
     * 修改入库管理详情列表
     * @param rkgl
     */
    private void uodateRkdxq(TbCkglRkckgl rkgl) {
        if(rkgl.getRkckdmxList()!=null && rkgl.getRkckdmxList().size()!=0){
            //首先恢复物品库存
            recoverWpkc(rkgl);
            //1.先根据入库管理ID批量删除
            Example example = new Example(TbCkglRkckdmx.class);
            example.createCriteria().andEqualTo("rkglId",rkgl.getId());
            rkdmxMapper.deleteByExample(example);
            InstaIdGenerator idGenerator = new InstaIdGenerator();
            for (TbCkglRkckdmx rkdmx : rkgl.getRkckdmxList()) {
                rkdmx.setId(String.valueOf(idGenerator.nextId(TimeUtil.timeGen())));
                rkdmx.setRkglId(rkgl.getId());
                rkdmx.setCkId(rkgl.getSzck());
            }
            rkdmxMapper.insertByList(rkgl.getRkckdmxList());
            //添加物品库存表
            addWpkcInfo(rkgl.getRkckdmxList());
        }
    }

    /**
     * 恢复物品库存
     * @param rkgl
     */
    private void recoverWpkc(TbCkglRkckgl rkgl) {
        Example example = new Example(TbCkglRkckdmx.class);
        example.createCriteria().andEqualTo("rkglId",rkgl.getId());
        //查询出之前的物品详情数量
        List<TbCkglRkckdmx> tbCkglRkckdmxes = rkdmxMapper.selectByExample(example);
        if(tbCkglRkckdmxes.size()>0){
            Example wpkcExample = new Example(TbCkglWpkc.class);
            wpkcExample.createCriteria().andEqualTo("ckId",tbCkglRkckdmxes.get(0).getCkId());
            //现有库存数量
            List<TbCkglWpkc> wpkcOld = wpkcMapper.selectByExample(wpkcExample);
            ArrayList<TbCkglWpkc> updateWpkc = new ArrayList<>();
            for (TbCkglRkckdmx wpmx : tbCkglRkckdmxes) {
                for (TbCkglWpkc wpkc : wpkcOld) {
                    if(wpmx.getWpId().equals(wpkc.getWpId())){
                        wpkc.setSl(String.valueOf(Integer.parseInt(wpkc.getSl())
                                -Integer.parseInt(wpmx.getSl())));
                        updateWpkc.add(wpkc);
                    }
                }
            }
            //批量恢复物品库存
            if(updateWpkc.size()>0){
                for (TbCkglWpkc wpkc : updateWpkc) {
                    wpkcMapper.updateByPrimaryKeySelective(wpkc);
                }
            }
        }
    }

    /**
     * 添加入库单详情
     * @param rkgl
     */
    private void addRkdxq(TbCkglRkckgl rkgl) {
        if(rkgl.getRkckdmxList()!=null && rkgl.getRkckdmxList().size()!=0){
            InstaIdGenerator idGenerator = new InstaIdGenerator();
            for (TbCkglRkckdmx rkdmx : rkgl.getRkckdmxList()) {
                rkdmx.setId(String.valueOf(idGenerator.nextId(TimeUtil.timeGen())));
                rkdmx.setRkglId(rkgl.getId());//入库单ID
                rkdmx.setCkId(rkgl.getSzck());//仓库ID
            }
            rkdmxMapper.insertByList(rkgl.getRkckdmxList());
            //添加物品库存表
            addWpkcInfo(rkgl.getRkckdmxList());
        }
    }

    /**
     * 添加物品库存
     * @param rkckdmxList
     */
    private void addWpkcInfo(List<TbCkglRkckdmx> rkckdmxList) {
        //先根据仓库ID查询出本仓库的物品数据
        Example wpkcExample = new Example(TbCkglWpkc.class);
        wpkcExample.createCriteria().andEqualTo("ckId",rkckdmxList.get(0).getCkId());
        List<TbCkglWpkc> wpkcOld = wpkcMapper.selectByExample(wpkcExample);
        //然后做数据对比
        List<TbCkglWpkc> wpkcNew = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        InstaIdGenerator idGenerator = new InstaIdGenerator();
        if(wpkcOld.size()==0){
            for (TbCkglRkckdmx rkckdmx : rkckdmxList) {
                addwpkcNew(rkckdmx,wpkcNew,idGenerator);
            }
        }else {
            for (TbCkglRkckdmx rkckdmx : rkckdmxList) {
                int i = 0 ;
                for (TbCkglWpkc oldWpkc : wpkcOld) {
                    //将明细单物品ID和库存数据物品ID对比
                    if(rkckdmx.getWpId().equals(oldWpkc.getWpId())){
                        //如果一致的话 将数量修改
                        oldWpkc.setSl(String.valueOf(Integer.parseInt(oldWpkc.getSl())+Integer.parseInt(rkckdmx.getSl())));
                        wpkcNew.add(oldWpkc);
                        ids.add(oldWpkc.getId());
                        i=1;
                        break;
                    }
                }
                if(i==0){
                    addwpkcNew(rkckdmx,wpkcNew,idGenerator);
                }
            }
            //原来的重复的数据删除掉
            if(ids.size()>0){
                wpkcMapper.deleteByIds(ids);
            }

        }
        //将过滤过的数据添加到数据库中
        wpkcMapper.insertByList(wpkcNew);

    }

    private void addwpkcNew(TbCkglRkckdmx rkckdmx, List<TbCkglWpkc> wpkcNew,InstaIdGenerator idGenerator) {
        TbCkglWpkc wpkc = new TbCkglWpkc();
        wpkc.setId(String.valueOf(idGenerator.nextId(TimeUtil.timeGen())));
        wpkc.setCkId(rkckdmx.getCkId());
        wpkc.setSl(rkckdmx.getSl());
        wpkc.setWpId(rkckdmx.getWpId());
        wpkc.setCreateTime(new Date());
        wpkc.setUpdateTime(new Date());
        wpkc.setUserId(rkckdmx.getUserId());
        TbCkglWpda wpda = wpdaMapper.selectByPrimaryKey(rkckdmx.getWpId());
        if(wpda!=null){
            wpkc.setWpdm(wpda.getWpdm());
            wpkc.setWplb(wpda.getWplb());
            wpkc.setWpmc(wpda.getWpmc());
            wpkc.setWpxh(wpda.getWpxh());
            wpkc.setDj(String.valueOf(wpda.getKcpjj()));
            wpkc.setDw(wpda.getDw());
            wpkc.setJe(String.valueOf(wpda.getKcpjj()));
            wpkcNew.add(wpkc);
        }
    }

    /**
     * 根据主键查询
     * @param id
     * @return
     */
    @Override
    public Result getById(String id) {
        if(StringUtil.isEmpty(id)){
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        TbCkglRkckgl rkgl = rkglMapper.selectByPrimaryKey(id);
        if(rkgl==null){
            return Result.success();
        }
        //根据入库管理ID查询入库单明细
        Example example = new Example(TbCkglRkckdmx.class);
        example.createCriteria().andEqualTo("rkglId",rkgl.getId());
        List<TbCkglRkckdmx> tbCkglRkdmxes = rkdmxMapper.selectByExample(example);
        rkgl.setRkckdmxList(tbCkglRkdmxes);
        return Result.success(rkgl);
    }
    /**
     * 列表页面查询
     * @param map
     * @return
     */
    @Override
    public Result pageList(Map<String,Object> map) {
        if(isNotNull(map)){//参数验证
            Map<String,Object> dataMap = new HashMap<>();
            Example example = new Example(TbCkglRkckgl.class);
            PageHelper.startPage((Integer) map.get("pageNum"),(Integer)map.get("pageSize"));
            //setExample(example,map);//添加查询条件
            //Page<TbCkglRkckgl> pageList = (Page<TbCkglRkckgl>) rkglMapper.selectByExample(example);
            map.put("djlb","0");
            Page<TbCkglRkckgl> pageList = rkglMapper.pageList(map);
            dataMap.put("data",pageList.getResult());
            dataMap.put("totle",pageList.getTotal());
            return Result.success(dataMap);
        }
        return Result.error(CodeMsg.INTER_ERROR);
    }

    /**
     * 添加列表查询条件
     * @param example
     * @param map
     */
    private void setExample(Example example, Map<String, Object> map) {
        example.setOrderByClause("UPDATE_TIME DESC");
        Example.Criteria criteria = example.createCriteria().andEqualTo("djlb","0")
                .andEqualTo("userId",map.get("userId"));
        criteria.andEqualTo("zfbj","0");
        if(StringUtils.isNotEmpty(String.valueOf(map.get("szck")))){
            criteria.andEqualTo("szck",String.valueOf(map.get("szck")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("jsr")))){
            criteria.andLike("jsr",String.valueOf(map.get("jsr")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("codeId")))){//制单人
            criteria.andLike("codeId",String.valueOf(map.get("codeId")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("shzt")))){
            criteria.andLike("shzt",String.valueOf(map.get("shzt")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("ksrq")))){
            criteria.andGreaterThanOrEqualTo("fsrq",String.valueOf(map.get("ksrq")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("jsrq")))){
            criteria.andLessThanOrEqualTo("fsrq",String.valueOf(map.get("jsrq")));
        }

    }

    /**
     * 根据ids 批量删除
     * @param ids 主键ids数组
     * @return
     */
    @Override
    public Result deleteByIds(List<String> ids) {
        if (ids.size() == 0) {
            return  Result.error(CodeMsg.INTER_ERROR,null);
        }
        TbCkglRkckgl tbCkglRkckgl = new TbCkglRkckgl();
        tbCkglRkckgl.setZfbj("1");
        Example example = new Example(TbCkglCkda.class);
        example.createCriteria().andIn("id",ids);
        int result = rkglMapper.updateByExampleSelective(tbCkglRkckgl,example);
        if (result == ids.size()) {
            return  Result.success(CodeMsg.SUCCESS);
        }
        return Result.error(CodeMsg.INTER_ERROR, null);
    }

    /**
     *验证map参数
     */
    private Boolean isNotNull(Map<String,Object> map) {
        if(StringUtil.isEmpty(String.valueOf(map.get("pageNum")) )|| StringUtil.isEmpty(String.valueOf(map.get("pageSize")))){
            return false;
        }
        return true;
    }

}
